﻿using Microsoft.AspNetCore.Mvc;
using WoodAdmin.Common.Attribute;
using WoodAdmin.Models;
using WoodAdmin.Models.ViewModels;
using WoodAdmin.Services;
using SqlSugar;
using System;
using System.Collections.Generic;
using SqlSugar.Extensions;

namespace WoodAdmin.Controllers
{
    public class AccessController : BaseController
    {
        private readonly AccessService _service;
        private readonly SysNodeService _node;

        public AccessController(AccessService service,SysNodeService node)
        {
            _service = service;
            _node = node;
        }

        #region 列表 
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [SkipCheckPermission]
        public IActionResult Index(int id)
        {
            ViewBag.RoleId = id;
            return View();
        }

        /// <summary>
        /// 获取节点树
        /// </summary>
        /// <returns></returns>
        [SkipCheckPermission]
        public IActionResult NodeStructure(int id)
        {
            using (var db = DbContext.Db)
            {
                //角色权限节点
                var roleNodes = db.Queryable<SysAccess>().Where(a => a.RoleID == id);
                //所有节点
                var allNodes = db.Queryable<SysNode>();
                //联查（所有节点+角色权限节点中的ID）
                var nodesWithChecked = db.Queryable(allNodes, roleNodes, JoinType.Left, (a1, a2) => a1.ID == a2.NodeID)
                                                  .Select((a1, a2) => new
                                                  {
                                                      id = a1.ID,
                                                      title = a1.Title,
                                                      parentId = a1.Pid,
                                                      checkArr = a2.ID > 0 ? "[{ \"type\":\"0\",\"checked\":\"1\"}]" : "[{ \"type\":\"0\",\"checked\":\"0\"}]"
                                                  }).ToList();

                return Json(new DTreeModel { status = new Status { code = 200, message = "操作成功" }, data = nodesWithChecked });
            }
        }
        #endregion

        #region 编辑
        /// <summary>
        /// 保存编辑
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [SkipCheckPermission]
        public IActionResult AddEdit(string nodeIds,int roleid)
        {
            string[] idArr = nodeIds.Split(',');
            if (idArr.Length<=0 || roleid<=0)
            {
                return JsonError(APPKeys.Failed);
            }
            using (var db = DbContext.Db)
            {
                //删除角色原有节点权限
                var orginIdArr = db.Queryable<SysAccess>().Where(a => a.RoleID == roleid).Select(a => a.RoleID);
                var rs1 = db.Deleteable<SysAccess>().In(a => a.RoleID, orginIdArr).ExecuteCommand();

                //重新添加角色节点权限
                var newIdList = new List<SysAccess>();
                foreach (var id in idArr)
                {
                    SysAccess acc = new SysAccess
                    {
                        CreateMan = 1,
                        CreateTime = DateTime.Now,
                        DelFlag = 0,
                        NodeID = id.ObjToInt(),
                        RoleID = roleid
                    };
                    newIdList.Add(acc);
                }
                var rs2 = db.Insertable(newIdList.ToArray()).ExecuteCommand();
                if (rs2 > 0)
                {
                    return JsonSuccess();
                }
                return JsonError();
            }
        }

        #endregion
    }
}